<template>
  <div>
    <!-- 查询条件表单 -->
    <el-form :inline="true" :model="queryParams" class="demo-form-inline">
      <el-form-item label="订单编号">
        <el-input v-model="queryParams.orderNum" placeholder="请输入订单编号"></el-input>
      </el-form-item>
      <el-form-item label="用户电话号">
        <el-input v-model="queryParams.userPhone" placeholder="请输入用户电话号"></el-input>
      </el-form-item>
      <el-form-item label="用户名">
        <el-input v-model="queryParams.userName" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="用户收货地址">
        <el-input v-model="queryParams.userAddress" placeholder="请输入用户收货地址"></el-input>
      </el-form-item>
      <el-form-item label="订单状态" style="width: 300px;">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态">
          <el-option label="全部" value=""></el-option>
          <el-option label="未支付" value="0"></el-option>
          <el-option label="已支付" value="1"></el-option>
          <el-option label="商家备餐中" value="2"></el-option>
          <el-option label="配送中" value="3"></el-option>
          <el-option label="已送达" value="4"></el-option>
          <el-option label="已取消" value="5"></el-option>
          <el-option label="已退款" value="6"></el-option>
          <el-option label="等待商家接单" value="7"></el-option>
          <el-option label="结束订单" value="8"></el-option>
          <el-option label="异常订单" value="9"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单创建时间">
        <div class="block">
          <el-date-picker
            v-model="queryParams.orderStartTime"
            type="datetime"
            placeholder="请选择时间"
          />
        </div>
      </el-form-item>
      <el-form-item label="订单创建时间">
        <div class="block">
          <el-date-picker
            v-model="queryParams.orderEndTime"
            type="datetime"
            placeholder="请选择时间"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 订单表格 -->
    <el-table
      :data="paginatedOrders"
      style="width: 100%"
      border
      stripe
      @row-click="handleRowClick"
    >
      <el-table-column
        prop="orderId"
        label="订单号"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="userName"
        label="客户姓名"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="consignee"
        label="收货人"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="addressName"
        label="收货地址"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="consigneePhone"
        label="收货电话"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="createTime"
        label="订单日期"
        width="180"
      >
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="orderAmount"
        label="总金额"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="orderState"
        label="订单状态"
        width="180"
      >
        <template #default="scope">
          {{ orderStateText(scope.row.orderState) }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="mini"
            @click="handleEdit(row)"
          >查看详情</el-button>
          <el-button
            type="primary"
            size="mini"
            @click="handleTrack(row)"
          >流程跟踪</el-button>
          <el-button
            type="danger"
            size="mini"
            @click="refundOrder(row)"
            v-if="row.orderState === 2"
          >退款</el-button>
          <el-button
              type="danger"
              size="mini"
              @click="handleDelete(row)"
              v-if="row.orderState === 7"
          >接单</el-button>
          <el-button
              type="success"
              size="mini"
              @click="drlivering(row)"
              v-if="row.orderState === 2"
          >配送</el-button>
          <el-button
              type="success"
              size="mini"
              @click="drlivery(row)"
              v-if="row.orderState === 3"
          >送达</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next, sizes, total"
        :total="total"
        :page-size="queryParams.pageSize"
        :current-page="queryParams.pageNum"
        :page-sizes="[2, 3, 5, 10]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 订单详情模态框 -->
    <el-dialog
      title="订单详情"
      v-model="dialogVisible"
      width="60%"
    >
      <h4>商品详情:</h4>
      <el-table :data="orderDetail" style="width: 100%">
        <el-table-column prop="name" label="商品名称" width="180"></el-table-column>
        <el-table-column prop="count" label="数量" width="180"></el-table-column>
        <el-table-column prop="price" label="单价"></el-table-column>
        <el-table-column prop="totalPrice" label="总价"></el-table-column>
        <el-table-column prop="disCount" label="折扣"></el-table-column>
        <el-table-column prop="disTotalPrice" label="折后价"></el-table-column>
        <el-table-column prop="storeProductImg" label="商品图片">
          <template #default="scope">
            <img :src="scope.row.storeProductImg" alt="" style="width: 100px;height: 100px">
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 流程跟踪模态框 -->
    <el-dialog
      title="流程跟踪"
      v-model="trackDialogVisible"
      width="60%"
      class="track-dialog"
    >
      <el-timeline class="custom-timeline">
        <el-timeline-item
          v-for="(activity, index) in trackActivities"
          :key="index"
          placement="top"
          class="timeline-item"
        >
          <el-card shadow="hover" class="timeline-card">
            <el-row>
              <el-col :span="12">
                <p class="activity-timestamp">{{ activity.timestamp }}</p>
              </el-col>
              <el-col :span="4">
                <p class="activity-content">{{ activity.content }}</p>
              </el-col>
            </el-row>
          </el-card>
        </el-timeline-item>
      </el-timeline>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="trackDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import moment from 'moment-timezone';
import refund from "@/components/meals/view/Refund.vue";
import { ElMessage } from "element-plus";

export default {
  name: 'OrderInfo',
  data() {
    return {
      dialogVisible: false,
      trackDialogVisible: false,
      // 查询条件
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        orderNum: null,
        userPhone: null,
        userName: null,
        userAddress: null,
        orderStatus: null,
        orderStartTime: null,
        orderEndTime: null,
      },
      orderDetail: [],
      trackActivities: [],
      // 订单数据
      orders: [],
      total: 0,
      // 定时器
      timer: null,
    };
  },
  computed: {
    refund() {
      return refund;
    },
    // 根据查询条件过滤订单
    filteredOrders() {
      return this.orders.filter(order => {
        return (
          (!this.queryParams.orderNum || order.orderNum.includes(this.queryParams.orderNum)) &&
          (!this.queryParams.userPhone || order.userPhone.includes(this.queryParams.userPhone)) &&
          (!this.queryParams.userName || order.userName.includes(this.queryParams.userName)) &&
          (!this.queryParams.userAddress || order.addressName.includes(this.queryParams.userAddress)) &&
          (!this.queryParams.orderStatus || order.orderState === parseInt(this.queryParams.orderStatus)) &&
          (!this.queryParams.orderStartTime || new Date(order.createTime) >= new Date(this.queryParams.orderStartTime)) &&
          (!this.queryParams.orderEndTime || new Date(order.createTime) <= new Date(this.queryParams.orderEndTime))
        );
      });
    },
    // 分页后的订单数据
    paginatedOrders() {
      const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
      const end = start + this.queryParams.pageSize;
      return this.filteredOrders.slice(start, end);
    }
  },
  methods: {
    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1; // 查询时重置到第一页
      this.getOrders();
    },
    // 重置查询条件
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 5,
        orderNum: null,
        userPhone: null,
        userName: null,
        userAddress: null,
        orderStatus: null,
        orderStartTime: null,
        orderEndTime: null,
      };
    },
    drlivery(row) {
      axios.put("/meals/orderProduct/updateOrderArrived", {
        orderId: row.orderId
      }).then((response) => {
        if (response.data.code === 200) {
          ElMessage.success(response.data.msg);
          this.getOrders();
        } else {
          ElMessage.error(response.data.msg);
        }
      });
    },
    drlivering(row) {
      axios.put("/meals/orderProduct/updateOrderDeliver", {
        orderId: row.orderId
      }).then((response) => {
        if (response.data.code === 200) {
          ElMessage.success(response.data.msg);
          this.getOrders();
        } else {
          ElMessage.error(response.data.msg);
        }
      });
    },
    // 退款，取消订单
    refundOrder(row) {
      axios.put("/meals/orderProduct/updateOrderCancel", {
        orderId: row.orderId
      }).then((response) => {
        if (response.data.code === 200) {
          ElMessage.success(response.data.msg);
          this.getOrders();
        } else {
          ElMessage.error(response.data.msg);
        }
      });
    },
    // 编辑订单
    handleEdit(row) {
      const productIds = JSON.parse(row.productIds);
      this.orderDetail = productIds;
      this.getStoreProducts(productIds);
      this.dialogVisible = true;
    },
    getStoreProducts(products) {
      products.forEach(product => {
        axios.get("/meals/storeProduct/searchStoreProductDetail", {
          params: {
            productId: product.productId
          }
        }).then(res => {
          this.orderDetail.forEach(item => {
            if (item.productId === product.productId) {
              item.name = res.data.data.productName;
            }
          });
        });
      });
    },
    // 删除订单
    handleDelete(row) {
      // 实现删除订单逻辑
    },
    // 点击行
    handleRowClick(row, column, event) {
      console.log('点击行', row);
    },
    // 每页条数改变
    handleSizeChange(newSize) {
      this.queryParams.pageSize = newSize;
      this.queryParams.pageNum = 1; // 重置到第一页
      this.getOrders();
    },
    // 当前页改变
    handleCurrentChange(newPage) {
      this.queryParams.pageNum = newPage;
      this.getOrders();
    },
    getOrders() {
      axios
        .get("/meals/orderProduct/getStorePageOrder", {
          params: this.queryParams
        })
        .then((response) => {
          if (response.data && response.data.data) {
            this.total = response.data.data.total;
            this.orders = response.data.data.list.map((order) => {
              try {
                order.productDetails = JSON.parse(order.productIds);
              } catch (e) {
                order.productDetails = [];
              }
              return order;
            });
          } else {
            this.$message.error(response.data.msg);
          }
        })
        .catch(() => {
          this.$message.error("获取订单列表失败！");
        });
    },
    orderStateText(state) {
      const states = {
        0: "未支付",
        1: "已支付",
        2: "商家备餐中",
        3: "配送中",
        4: "已送达",
        5: "已取消",
        6: "已退款",
        7: "等待商家接单",
        8: "结束订单",
        9: "异常订单",
      };
      return states[state] || "未知状态";
    },
    formatDateTime(date) {
      return moment(date).tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss');
    },
    // 处理流程跟踪
    handleTrack(row) {
      this.getTrackActivities(row.orderId);
      this.trackDialogVisible = true;
    },
    // 获取流程跟踪信息
    getTrackActivities(orderId) {
      axios.get("/meals/orderLog/getOrderLog", {
        params: {
          orderId: orderId
        }
      }).then(response => {
        if (response.data.code === 200) {
          this.trackActivities = response.data.data.map(activity => ({
            timestamp: this.formatDateTime(activity.createTime),
            title: activity.orderStateText,
            content: activity.orderDesc,
            file: activity.fileName // 假设每个活动有一个文件名属性
          }));
        } else {
          ElMessage.error(response.data.msg);
        }
      }).catch(() => {
        ElMessage.error("获取流程跟踪信息失败！");
      });
    },
    // 启动定时器
    startPolling() {
      this.timer = setInterval(() => {
        this.getOrders();
      }, 60000); // 每隔60秒（1分钟）查询一次
    },
    // 停止定时器
    stopPolling() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    }
  },
  mounted() {
    this.getOrders();
    this.startPolling(); // 启动定时器
  },
  beforeUnmount() {
    this.stopPolling(); // 清除定时器
  }
};
</script>

<style scoped>
.demo-form-inline {
  margin-bottom: 20px;
}

.track-dialog {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.custom-timeline {
  padding-left: 20px;
}

.timeline-item {
  margin-bottom: 20px;
}

.timeline-card {
  border-radius: 8px;
  border: 1px solid #ebeef5;
  transition: box-shadow 0.3s ease;
  padding: 20px;
}

.timeline-card:hover {
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.activity-title {
  font-size: 18px;
  font-weight: bold;
  margin: 0;
  color: #303133;
}

.activity-timestamp {
  font-size: 14px;
  color: #909399;
  margin: 5px 0 0;
}

.activity-file {
  font-size: 14px;
  color: #606266;
  margin: 5px 0 0;
}

.activity-content {
  font-size: 14px;
  color: #606266;
  margin: 10px 0 0;
}

.dialog-footer {
  text-align: right;
  padding: 20px;
}

.el-button {
  margin-top: 20px;
}

.file-col {
  text-align: right;
}
</style>
